package com.xingkeduo.business.user.controller;

import com.xingkeduo.business.transformation.json.BaseDTOJTO;
import com.xingkeduo.business.transformation.json.ConsumerDTOJTO;
import com.xingkeduo.business.transformation.json.ConsumerJTO;
import com.xingkeduo.business.transformation.json.ConsumerPrivateJTO;
import com.xingkeduo.business.user.domain.ConsumerDomain;
import com.xingkeduo.pojo.dto.BaseDTO;
import com.xingkeduo.pojo.dto.WxEncryDTO;
import com.xingkeduo.pojo.dto.WxMaCodeDTO;
import com.xingkeduo.pojo.dto.WxMaUserInfo;
import com.xingkeduo.pojo.phppojo.ResponseResult;
import com.xingkeduo.pojo.query.ConsumerPrivateQO;
import com.xingkeduo.pojo.query.ConsumerQO;
import com.xingkeduo.pojo.utils.ResponseUtils;
import com.xingkeduo.util.pojo.base.BaseController;
import com.xingkeduo.util.pojo.exception.DataException;
import com.xingkeduo.util.tool.ReturnUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Description:
 * @Author:gaozifeng
 * @Date 2019/2/18 19:00
 **/
@Slf4j
@RestController
@RequestMapping("/consumer")
public class ConsumerController extends BaseController {

    @Autowired
    private ConsumerDomain consumerDomain;


    private static final String USERNOTEXIST = "用户不存在";

    private static final String USERAUTHCODEuserAuthCode = "9004";

    /**
     * 外部接口   根据id查询用户集合,查询用户集合
     *
     * @param id:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/9 18:20
     */
    @GetMapping("/getid/{id}")
    public ResponseUtils<List<Long>> getUserIds(@PathVariable String id) {
        try {
            ConsumerQO consumerQO = ConsumerJTO.createQueryForPrimary(id);
            List<Long> consumerIds = consumerDomain.getConsumerIds(consumerQO);
            return ResponseUtils.getSuccess(consumerIds);
        } catch (Throwable throwable) {
            dealException(throwable);
            return ResponseUtils.error(throwable.getMessage(), "-1");
        }
    }

    /**
     * 查询用户是否存在 不存在重新拉信息
     *
     * @param f_user_id:
     * @return : com.xingkeduo.pojo.utils.ResponseUtils<java.util.List<java.lang.Long>>
     * @author : gaozifeng
     * @date : 2019/7/31 19:00
     */
    @GetMapping("/checkid/{f_user_id}")
    public ResponseUtils<Long> checkUserExist(@PathVariable Long f_user_id,String mobile_type) {
        try {
            return ResponseUtils.getSuccess(consumerDomain.checkUserExist(f_user_id,mobile_type));
        } catch (Throwable throwable) {
            dealException(throwable);
            log.info("consumer  checkid error,userid[{}]", f_user_id);
            if (USERNOTEXIST.equals(throwable.getMessage())) {
                return ResponseUtils.error("用户信息更新中 请等待", USERAUTHCODEuserAuthCode);
            }
            return ResponseUtils.error(throwable.getMessage(), "-1");
        }
    }


    /**
     * 外部接口,提供小程序用户信息
     * openid/userid,login 查询返回信息
     *
     * @param :
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/8 13:59
     */

    @GetMapping("/getinfo/{condition}")
    public ResponseUtils<WxMaUserInfo> getConsumerInfo(@PathVariable String condition) {
        try {
            log.info("consumer/getinfo  查询条件---" + condition);
            ConsumerQO queryForPrimary = ConsumerJTO.createQuery(condition);
            ConsumerPrivateQO queryByOpenid = ConsumerPrivateJTO.createQueryByOpenid(condition);
            WxMaUserInfo consumerInfo = consumerDomain.getConsumerInfo(queryByOpenid, queryForPrimary);
            return ResponseUtils.getSuccess(consumerInfo);
        } catch (Throwable throwable) {
            dealException(throwable);
            if (USERNOTEXIST.equals(throwable.getMessage())) {
                return ResponseUtils.error("用户信息更新中 请等待", USERAUTHCODEuserAuthCode);
            }
            return ResponseUtils.error(throwable.getMessage(), "-1");
        }
    }

    /**
     * 根据条件查询用户信息
     *
     * @param :
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/4/28 19:19
     */
    @GetMapping("/getdetail/{condition}")
    public String getConsumer(@PathVariable String condition) {
        returnUtil = new ReturnUtil();
        try {
            ConsumerQO queryForList = ConsumerJTO.createQueryForCondition(condition);
            ConsumerPrivateQO queryCondition = ConsumerPrivateJTO.createQueryCondition(condition);
            String result = returnUtil.getSuccess(ConsumerDTOJTO.toJson(consumerDomain.getConsumerByCondition(queryForList, queryCondition)));
            log.info("getdetail,request:{}.response:{}",condition,result);
            return result;
        } catch (Throwable t) {
            return dealException(t, returnUtil);
        }
    }

    /**
     * 查询用户集合
     *
     * @param ids:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/6/21 20:30
     */
    @GetMapping("/getids/list")
    public String getIdsList(String ids) {
        returnUtil = new ReturnUtil();
        try {
            return returnUtil.getSuccess(ConsumerDTOJTO.toJson(consumerDomain.selectUserListForIds(ids)));
        } catch (Throwable t) {
            return dealException(t, returnUtil);
        }
    }

    /**
     * 外部接口 (订单) 根据用户id,昵称,手机号 查询用户list
     *
     * @param :
     * @return : com.xingkeduo.pojo.utils.ResponseUtils<com.xingkeduo.pojo.dto.WxMaUserInfo>
     * @author : gaozifeng
     * @date : 2019/7/5 11:49
     */
    @GetMapping("/list/condition/{searchName}")
    public ResponseUtils<Set<Long>> getUserIdsByCondition(@PathVariable String searchName) {
        try {
            ConsumerQO queryForList = ConsumerJTO.createQueryForCondition(searchName);
            ConsumerPrivateQO queryCondition = ConsumerPrivateJTO.createQueryCondition(searchName);
            return ResponseUtils.getSuccess(consumerDomain.getConsumerIdByCondition(queryForList, queryCondition));
        } catch (Throwable throwable) {
            return ResponseUtils.error(throwable.getMessage(), "-1");
        }
    }

    //php

    /**
     * 查询用户信息
     *
     * @param f_user_id
     * @param time
     * @param token
     * @param mobile_type
     * @return
     * @throws Throwable
     * @author : pantong
     */
    @GetMapping("/user")
    public Object getUserInfo(long f_user_id, String time, String token, String mobile_type) throws Throwable {
        try {
            Map<String, Object> map = consumerDomain.getUserInfo(f_user_id, time, token, mobile_type);
            return BaseDTOJTO.toSuccessJson(ConsumerPrivateJTO.toJsonForUserInfo(map));
        } catch (DataException e) {
            dealException(e);
            if (USERNOTEXIST.equals(e.getMessage())) {
                return BaseDTOJTO.toUserAuth("用户信息更新中 请等待");
            }
            return BaseDTOJTO.toErrorJson(e.getMessage());
        } catch (Exception e) {
            dealException(e);
            return BaseDTOJTO.toErrorJson(e.getMessage());
        }
    }

    /**
     * 查询用户基本信息
     *
     * @param f_user_id
     * @param time
     * @param token
     * @param mobile_type
     * @return
     * @throws Throwable
     * @author : pantong
     */
    @GetMapping("/getBasicUserInfo")
    public ResponseEntity getBasicUserInfo(long f_user_id, String time, String token, String mobile_type) throws Throwable {
        Map<String, Object> map = consumerDomain.getBasicUserInfo(f_user_id, time, token, mobile_type);
        return new ResponseEntity<>(ResponseUtils.getSuccess(map), HttpStatus.OK);
    }

    /**
     * 小程序新增    是走授权 再调用，这个只用于本地请求可删
     *
     * @param :
     * @return : void
     * @author : gaozifeng
     * @date : 2019/5/8 16:12
     */
    @GetMapping("/insert/Info")
    public String insertConsumerInfo() {
        returnUtil = new ReturnUtil();

        try {
            WxMaUserInfo body = new WxMaUserInfo();
            consumerDomain.insertConsumerInfo(body);
            return returnUtil.getSuccess();
        } catch (Throwable t) {
            return dealException(t, returnUtil);
        }
    }

    /**
     * 查询用户标签设置项
     *
     * @param f_user_id
     * @param time
     * @param token
     * @param mobile_type
     * @return
     * @throws Throwable
     * @author : pantong
     */
    @GetMapping("/revise_set")
    public Object revise_set(long f_user_id, String time, String token, String mobile_type) throws Throwable {
        try {
            Map<String, Object> map = consumerDomain.revise_set(f_user_id, time, token, mobile_type);
            return BaseDTOJTO.toSuccessJson(ConsumerPrivateJTO.toJsonForUserReviseSet(map));
        } catch (DataException e) {
            dealException(e);
            return BaseDTOJTO.toErrorJson(e.getMessage());
        } catch (Exception e) {
            dealException(e);
            return BaseDTOJTO.toErrorJson("操作失败，请稍后重试！");
        }
    }

    /**
     * 查询到店距离
     *
     * @param f_user_id
     * @param time
     * @param token
     * @param mobile_type
     * @return
     * @throws Throwable
     * @author : pantong
     */
    @GetMapping("/update_care")
    public Object selectDistance(long f_user_id, String time, String token, String mobile_type) throws Throwable {
        try {
            Map<String, Integer> map = consumerDomain.getUserDistance(f_user_id, time, token, mobile_type);
            return BaseDTOJTO.toSuccessJson(ConsumerPrivateJTO.toJsonDistance(map));
        } catch (DataException e) {
            dealException(e);
            return BaseDTOJTO.toErrorJson(e.getMessage());
        } catch (Exception e) {
            dealException(e);
            return BaseDTOJTO.toErrorJson("操作失败，请稍后重试！");
        }
    }

    /**
     * 修改到店距离
     *
     * @param f_user_id:
     * @param time:
     * @param token:
     * @param f_frequency:
     * @param mobile_type:
     * @return : java.lang.String
     * @throws Throwable
     * @author : pantong
     * @date : 2019/4/28 21:13
     */
    @GetMapping("/ajax_update_care")
    public Object ajax_update_care(long f_user_id, String time, String token, int f_frequency, String mobile_type) throws Throwable {
        try {
            consumerDomain.updateDistance(f_user_id, time, token, f_frequency, mobile_type);
            return new ResponseResult().success();
        } catch (Exception e) {
            dealException(e);
            return BaseDTOJTO.toErrorJson("修改失败，请稍后重试！");
        }
    }

    /**
     * 发送验证码
     *
     * @param f_user_id:
     * @param f_mobile:
     * @param time:
     * @param token:
     * @param mobile_type:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/4/29 20:27
     */
    @GetMapping("/ajax_send_sms_vertify_code")
    public Object sendSms(long f_user_id, String f_mobile, String time, String token, String mobile_type) {
        try {
            if (f_user_id < 0) {
                throw new DataException(DataException.Type.DEFAULT, "用户不能为空");
            }
            Map<String, Object> result = consumerDomain.sendSsm(f_user_id, f_mobile, time, token, mobile_type);
            return BaseDTOJTO.toSuccessJson(ConsumerPrivateJTO.toJsonForSendSms(result));
        } catch (Throwable throwable) {
            dealException(throwable);
            return new ResponseResult().exceptionForTransfer(null, throwable.getMessage());
        }
    }

    /**
     * 获取小程序授权code
     *
     * @param js_code:
     * @param mobile_type:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/8 13:58
     */
    @GetMapping("/code")
    public ResponseUtils<WxMaCodeDTO> code(String js_code, String mobile_type) {
        try {
            log.info("调用code------------------------" + js_code);
            WxMaCodeDTO code = consumerDomain.code(js_code, mobile_type);
            log.info("code" + code);
            return ResponseUtils.getSuccess(code);
        } catch (Throwable throwable) {
            dealException(throwable);
            return ResponseUtils.error();
        }
    }

    /**
     * 获取微信小程序用户信息
     *
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/4/30 16:05
     */
    @RequestMapping("/get_user_info")
    public ResponseUtils<BaseDTO> get_user_info(@RequestBody WxEncryDTO wxEncryDTO) {
        try {
            BaseDTO dto = consumerDomain.getWxUserInfo(wxEncryDTO.getEncryptedData(), wxEncryDTO.getIv(), wxEncryDTO.getSessionKey(), wxEncryDTO.getF_user_id(), wxEncryDTO.getMobile_type());
            return ResponseUtils.getSuccess(dto);
        } catch (Throwable throwable) {
            dealException(throwable);
            return ResponseUtils.error(throwable.getMessage(), "-1");
        }
    }

    /**
     * 小程序 更改用户手机号
     *
     * @param f_user_id:
     * @param f_code:
     * @param f_mobile:
     * @param time:
     * @param token:
     * @param mobile_type:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/2 20:50
     */
    @GetMapping("/ajax_update_mobile")
    public String bindingPhone(long f_user_id, String f_code, String f_mobile, String time, String token, String mobile_type) {
        try {
            consumerDomain.bindingPhone(f_user_id, f_code, f_mobile, time, token, mobile_type);
            return new ResponseResult().success(new ArrayList<>());
        } catch (Throwable throwable) {
            dealException(throwable);
            return new ResponseResult().exceptionForTransfer(new ArrayList<>(), throwable.getMessage());
        }
    }

}
